package cn.uniquesoft.controller.api;

import cn.uniquesoft.service.api.IMessageodeService;
import cn.uniquesoft.service.api.ITesteeApiService;
import cn.uniquesoft.util.*;
import cn.uniquesoft.vo.AnswerVO;
import cn.uniquesoft.vo.api.MessageodeVO;
import cn.uniquesoft.vo.api.TesteeApiVO;
import com.aliyuncs.dysmsapi.model.SendSmsResponse;
import com.aliyuncs.exceptions.ClientException;
import com.taobao.api.ApiException;
import com.taobao.api.DefaultTaobaoClient;
import com.taobao.api.TaobaoClient;
import com.taobao.api.domain.Userinfos;
import com.taobao.api.request.OpenimUsersAddRequest;
import com.taobao.api.response.OpenimUsersAddResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.List;

/**
 * 作者: wty 2017年12月07日 下午2:33:31 邮件: wangtianyi0722@163.com 描述: 注册
 */
@RestController
@RequestMapping(value = "/api/register")
public class RegisterController {
    @Autowired
    private ITesteeApiService testeeApiService;
    @Autowired
    private IMessageodeService messageodeService;
    @Autowired
    private HttpServletRequest request;
    @Value("${from-email.account}")
    private String fromEmailAccount;//配置的发送邮箱帐号
    @Value("${from-email.username}")
    private String fromEmailUserName;//配置的发送邮箱用户名
    @Value("${from-email.pwd}")
    private String fromEmailPwd;//配置的发送邮箱密码
    @Value("${validation.timeout}")
    private long validationTimeout;//验证超时

    //获取验证码
    @RequestMapping(value = "/sendCode/{cname}/{itype}/{acflag}")
    public AnswerVO sendCode(@PathVariable String cname, @PathVariable int itype, @PathVariable String acflag) {
        AnswerVO answerVO = new AnswerVO();
        answerVO.setSuccess(false);
        answerVO.setMsg("验证码请求错误，请稍后再试!");
        String ccode = "";//验证码
        if ("register".equals(acflag) && this.testeeApiService.getCount(cname, itype) > 0) {
            answerVO.setMsg("帐号已被注册！");
            return answerVO;
        }
        if("forget".equals(acflag) && this.testeeApiService.getCount(cname, itype) == 0){
            answerVO.setMsg("帐号不存在，请前往注册！");
            return answerVO;
        }
        //判断之前有效期内有没有发送过验证码，若发送过，重新发送相同验证码
        boolean bflag = true;//有效期内没有发送过标识
        MessageodeVO messageodeVO = this.messageodeService.findFirstItem(cname);//根据帐号查询验证码对象
        if (null == messageodeVO || DateUtil.getCurrentMills() - messageodeVO.getDsendtime().getTime() > validationTimeout) {//若有效期内没有发送过
            ccode = AuthenticationUtil.authCode();
        } else {
            bflag = false;
            ccode = messageodeVO.getCcode();
        }
        System.out.println(ccode);
        //发送验证码
        try {
            if (0 == itype) {//邮箱
                answerVO = this.sendMailCode(cname, ccode, answerVO);
            } else {//手机
                answerVO = this.sendPhoneCode(cname, ccode, answerVO);
            }
            if (answerVO.isSuccess() && bflag) {
                messageodeService.saveCode(cname, ccode, itype);//将验证码存储到数据库
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return answerVO;
    }

    //发送邮箱验证
    public AnswerVO sendMailCode(String cname, String ccode, AnswerVO answerVO) throws Exception {
        //获取正确注册邮箱，发送验证码
        SendMailUtil.sendMail(fromEmailAccount, fromEmailUserName, fromEmailPwd, cname, "验证码", "<h5>您本次的验证码为：</h5>：<b>" + ccode + "</b><br/><span>验证码有效期为10分钟！</span>");
        answerVO.setSuccess(true);
        answerVO.setMsg("验证码已发送");
        return answerVO;
    }

    //发送手机验证码
    public AnswerVO sendPhoneCode(String cname, String ccode, AnswerVO answerVO) throws ClientException {
        //调用短信接口发送短信,已测试成功，现注释
//        SendSmsResponse sendSmsResponse = SmsSendUtil.sendSms(cname, ccode);
//        if (sendSmsResponse.getCode().equalsIgnoreCase("OK")) {
        answerVO.setSuccess(true);
        answerVO.setMsg("验证码已发送");
//        }
        return answerVO;
    }

    //检查验证码是否正确
    @RequestMapping(value = "/checkCode/{cname}/{ccode}")
    public AnswerVO checkAuthCode(@PathVariable String cname, @PathVariable String ccode) {
        AnswerVO answerVO = new AnswerVO();
        answerVO.setSuccess(false);
        answerVO.setMsg("验证码错误，请稍后再试!");
        MessageodeVO messageodeVO = this.messageodeService.findFirstItem(cname);//根据帐号查询验证码对象
        if (null == messageodeVO) {
            answerVO.setMsg("请先获取验证码!");
            return answerVO;
        }
        String authCode = messageodeVO.getCcode();//数据库中的验证码
        //获取当前时间
        if (DateUtil.getCurrentMills() - messageodeVO.getDsendtime().getTime() > validationTimeout) {
            answerVO.setMsg("验证码有效期已过，请重新获取验证码!");
            return answerVO;
        }
        if (ccode.length() == 0) {
            answerVO.setMsg("请输入验证码!");
            return answerVO;
        }
        if (ccode.toLowerCase().equals(authCode.toLowerCase())) {//不区分大小写验证
            answerVO.setSuccess(true);
            answerVO.setMsg("验证通过!");
            answerVO.setData(cname);
            return answerVO;
        }
        return answerVO;
    }

    //注册方法
    @RequestMapping(value = "/register/{cname}/{pwd}/{ccode}/{itype}/{ctype}")
    public AnswerVO register(@PathVariable String cname, @PathVariable String pwd, @PathVariable String ccode, @PathVariable int itype, @PathVariable int ctype) {
        AnswerVO answerVO = new AnswerVO();
        answerVO.setSuccess(false);
        answerVO.setMsg("注册未成功！");
        try {
            if (this.testeeApiService.getCount(cname, itype) > 0) {
                answerVO.setMsg("帐号已被注册！");
                return answerVO;
            }
            answerVO = this.checkAuthCode(cname, ccode);
            //验证码校验不通过直接返回失败
            if (!answerVO.isSuccess()) {
                return answerVO;
            }
            //考生信息插入到testee数据库表中
            TesteeApiVO testeeApiVO = this.testeeApiService.register(cname, pwd, itype,ctype);
            TaobaoClient client=new DefaultTaobaoClient("http://gw.api.taobao.com/router/rest", "24780111", "200ec76fee11a32092ae563119a9d4b7");
            OpenimUsersAddRequest req = new OpenimUsersAddRequest();
            List<Userinfos> userinfos = new ArrayList<Userinfos>();
            Userinfos obj = new Userinfos();
            obj.setUserid(cname);
            obj.setPassword(pwd);
            userinfos.add(obj);
            req.setUserinfos(userinfos);
            OpenimUsersAddResponse rsp = client.execute(req);
            String json = rsp.getBody();
            if (null != testeeApiVO) {
                answerVO.setSuccess(true);
                answerVO.setMsg("注册成功！");
                answerVO.setData(testeeApiVO);
                LogUtil.addlog(testeeApiVO,request);
            }
        } catch (ApiException e) {
            e.printStackTrace();
        }
        return answerVO;
    }

    //通过绑定注册方法
    @RequestMapping(value = "/registerByBind")
    public AnswerVO registerByBind(@RequestBody TesteeApiVO testeeApiVO) {
        AnswerVO answerVO = new AnswerVO();
        answerVO.setSuccess(false);
        answerVO.setMsg("注册未成功！");
        if (this.testeeApiService.getCount(testeeApiVO.getCname(), testeeApiVO.getItype()) > 0) {
            answerVO.setMsg("帐号已被注册！");
            return answerVO;
        }
        answerVO = this.checkAuthCode(testeeApiVO.getCname(), testeeApiVO.getCcode());
        //验证码校验不通过直接返回失败
        if (!answerVO.isSuccess()) {
            return answerVO;
        }
        //考生信息插入到testee数据库表中
        testeeApiVO = this.testeeApiService.registerByBind(testeeApiVO);
        if (null != testeeApiVO) {
            answerVO.setSuccess(true);
            answerVO.setMsg("注册成功！");
            answerVO.setData(testeeApiVO);
            LogUtil.addlog(testeeApiVO,request);
        }
        return answerVO;
    }


    //修改密码
    @RequestMapping(value = "/updatePassword/{cname}/{pwd}/{itype}")
    public AnswerVO updatePassword(@PathVariable String cname, @PathVariable String pwd, @PathVariable int itype){
        AnswerVO answerVO = new AnswerVO();
        answerVO.setSuccess(false);
        answerVO.setMsg("修改失败");
        int count = this.testeeApiService.updatePassword(cname,pwd,itype);
        if(count > 0){
            answerVO.setSuccess(true);
            answerVO.setMsg("修改成功，请重新登录");
        }
        return answerVO;
    }
}
